﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;
using System.Text.RegularExpressions;

namespace Extented.UI.Core.Helpers
{
    internal static class SystemWebAssemblyLoader
    {
        static SystemWebAssemblyLoader()
        {
            int clrMajorVersion = 2;
            try
            {
                clrMajorVersion = GetClrMajorVersion();
            }
            catch (SecurityException)
            {
            }
            if (clrMajorVersion == 2)
                systemWeb = Load("System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a");
            if (clrMajorVersion == 4 || systemWeb == null)
                systemWeb = Load("System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a");
        }
        static Assembly Load(string name)
        {
            try
            {
                return Assembly.Load(name);
            }
            catch (FileNotFoundException)
            {
                return null;
            }
        }
        static int GetClrMajorVersion()
        {
            int clrVersion = 0;
            string versionStr = RuntimeEnvironment.GetSystemVersion();
            Regex regex = new Regex("[0-9]", RegexOptions.Compiled | RegexOptions.Singleline);
            Match match = regex.Match(versionStr);
            if (match.Success)
                int.TryParse(match.Value, out clrVersion);
            return clrVersion;
        }
        static readonly Assembly systemWeb;
        public static Assembly SystemWeb
        {
            get { return systemWeb; }
        }
    }
}
